package cn.lg.soar.common.util.reflect;

import cn.lg.soar.common.util.data.DataUtil;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;

import java.util.Collection;
import java.util.Set;
import java.util.function.Consumer;

/**
 * 类扫描工具
 * @author luguoxiang
 * @date 2021/8/17
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
public interface ClassUtils {

    /**
     * 扫描包下所有类
     * @param packages
     * @param consumer
     */
    static void scan(String packages, Consumer<Class<?>> consumer) {
        scan(DataUtil.arrayToList(packages.split(",")), consumer);
    }

    /**
     * 扫描包下所有类
     * @param packages
     * @param consumer
     */
    static void scan(Collection<String> packages, Consumer<Class<?>> consumer) {
        ClassPathScanningCandidateComponentProvider scanner = new ClassPathScanningCandidateComponentProvider(false);
        scanner.addIncludeFilter((metadataReader, metadataReaderFactory) -> true);
        try {
            for (String s : packages) {
                Set<BeanDefinition> candidateComponents = scanner.findCandidateComponents(s);
                for (BeanDefinition candidateComponent : candidateComponents) {
                    Class<?> x = Class.forName(candidateComponent.getBeanClassName());
                    consumer.accept(x);
                }
            }
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

}
